package org.nt4b.schemadoc.core.dao.oracle;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.nt4b.schemadoc.core.dom.Column;
import org.nt4b.schemadoc.core.dom.Table;
import org.springframework.jdbc.core.RowMapper;


public class ColumnCommentsMapper implements RowMapper<Column> {
    protected Logger logger = Logger.getLogger(ColumnCommentsMapper.class);
    
    private Map<String, Table> tablesMap;
    
    ColumnCommentsMapper() {
    }
    
    public ColumnCommentsMapper(final List<Table> tables) {
        tablesMap = new HashMap<String, Table>();
        for (final Table table : tables) {
            tablesMap.put(table.getName(), table);
        }
    }
    
    @Override
    public Column mapRow(final ResultSet rs, final int rowNum) throws SQLException {
        final String tableName = rs.getString("TABLE_NAME");
        final String columnName = rs.getString("COLUMN_NAME");
        final String comment = rs.getString("COMMENTS");
        final String escapedComment;
        if (comment != null) {
            escapedComment = SqlStringEscaper.escape(comment);
        } else {
            escapedComment = "";
        }
        
        final Column column = new Column();
        column.setName(columnName);
        column.setComment(escapedComment);
        
        final Table table = tablesMap.get(tableName);
        if (table != null) {
            // Table found
            List<Column> columns = table.getColumns();
            if (columns == null) {
                columns = new ArrayList<Column>();
                table.setColumns(columns);
            }
            
            columns.add(column);
            
            if (logger.isDebugEnabled()) {
                logger.debug("read comments for table: " + tableName + " column: " + columnName);
            }
        }
        
        return column;
    }
    
}
